package com.jp.knowledge.my.activity;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jp.knowledge.R;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.logic.PersonLogic;
import com.jp.knowledge.my.fragment.ReviewOrganizeFragment;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.view.TabView;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 528787067@qq.com on 2017/4/14.
 */

public class ReviewOrganizeActivity extends SlidingActivity implements View.OnClickListener, ReviewOrganizeFragment.DataEmptyListener {

    @ViewInject(R.id.data_show_view)
    private LinearLayout dataShowView;
    @ViewInject(R.id.tab_view)
    private TabView tabView;
    @ViewInject(R.id.review_viewpager)
    private ViewPager contentView;
    @ViewInject(R.id.no_review_view)
    private LinearLayout noReviewView;
    @ViewInject(R.id.refresh)
    private CanRefreshLayout refreshLayout;

    private List<String> tabNames;
    private List<OrganizaModel> companyList;
    private List<Fragment> pagerFragment;
    private PagerAdapter pagerAdapter;

    private PersonLogic personLogic;
    private LocalBroadCast localBroadCast;
    private LocalBroadcastManager localBroadcastManager;

    @Override
    protected int getResourceId() {
        return R.layout.activity_review_organize;
    }

    @Override
    protected void init() {
        tabView.setTag(getIntent().getStringExtra("companyId"));
        tabNames = new ArrayList<>();
        initData();
        initTitleBar();
        initView();
        initBroadcast();
        refreshLayout.autoRefresh();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        tabView.setTag(intent.getStringExtra("companyId"));
        refreshLayout.autoRefresh();
    }

    private void initData(){
        companyList = getCompanys();
        personLogic = new PersonLogic(mContext);
        if(pagerFragment == null)
            pagerFragment = new ArrayList<>();
        else
            pagerFragment.clear();
        for(OrganizaModel organizaModel : companyList){
            String id;
            int type = organizaModel.getCompanyType();
            if(type == 2)
                id = organizaModel.getClassId();
            else
                id = organizaModel.getCompanyId();
            ReviewOrganizeFragment fragment = ReviewOrganizeFragment.newInstance(id, type);
            fragment.setDataEmptyListener(this);
            pagerFragment.add(fragment);
        }
    }

    private void initTitleBar(){
        topName.setText("加入审核");
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        leftIcon.setOnClickListener(this);
        rightIcon.setVisibility(View.GONE);
    }

    private void initView(){
        setTabLayout();
        pagerAdapter = new PagerAdapter(getSupportFragmentManager());
        contentView.setAdapter(pagerAdapter);
        tabView.setupWithViewPager(contentView);
        setViewVisibility();
        refreshLayout.setOnLoadMoreListener(new CanRefreshLayout.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                personLogic.getUserData();
            }
        });
        refreshLayout.setOnRefreshListener(new CanRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                personLogic.getUserData();
            }
        });
        refreshLayout.setLoadMoreEnabled(false);
    }

    private void initBroadcast(){
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
            @Override
            public void done(Context context, Intent intent) {
                initData();
                pagerAdapter.notifyDataSetChanged();
                setTabLayout();
                setViewVisibility();
                refreshLayout.refreshComplete();
                refreshLayout.loadMoreComplete();
            }
        });
        localBroadcastManager.registerReceiver(localBroadCast, new IntentFilter(LocalBroadCast.GET_LOGIN_INFO));
    }

    @Override
    protected void onDestroy() {
        personLogic.getUserData();
        localBroadcastManager.unregisterReceiver(localBroadCast);
        super.onDestroy();
    }

    private void setTabLayout(){
        tabNames.clear();
        for(int i = 0; i < companyList.size(); i++) {
            String tabName = companyList.get(i).getCompanyFullName();
            if(tabName == null)
                tabName = "";
            tabNames.add(tabName);
        }
		if(tabView.getTag() != null){
			String companyId = (String) tabView.getTag();
            tabView.setTag(null);
			for(int i = 0; i < companyList.size(); i++){
				if(companyId.equals(companyList.get(i).getCompanyId())) {
					contentView.setCurrentItem(i);
					break;
				}
			}
		}
        if(contentView.getAdapter() != null)
            tabView.setTabItems(tabNames);
    }

    private void setViewVisibility(){
        if(companyList.size() == 0){
            dataShowView.setVisibility(View.GONE);
            noReviewView.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.VISIBLE);
        } else{
            dataShowView.setVisibility(View.VISIBLE);
            noReviewView.setVisibility(View.GONE);
            refreshLayout.setVisibility(View.GONE);
        }
    }

    private List<OrganizaModel> getCompanys(){
        List<OrganizaModel> organizaModelList = new ArrayList<>();
        try {
            List<OrganizaModel> companyList = application.getUserData().getCompanyList();
            for(OrganizaModel organizaModel : companyList)
                if(organizaModel.getIsAudit() == 1 && organizaModel.getCompanyAdmin() == 1)
                    organizaModelList.add(organizaModel);
        } catch (Exception e){}finally {
            return organizaModelList;
        }
    }

    @Override
    public void onClick(View v) {
        if(v == leftIcon)
            onBackPressed();
    }

    @Override
    public void dataIsEmpty(ReviewOrganizeFragment fragment) {
        int index = pagerFragment.indexOf(fragment);
        pagerFragment.remove(fragment);
        pagerAdapter.notifyDataSetChanged();
        OrganizaModel organizaModel = companyList.remove(index);
        organizaModel.setIsAudit(0);
        setViewVisibility();
        setTabLayout();
    }

    private class PagerAdapter extends FragmentStatePagerAdapter{
        public PagerAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int position) {
            return pagerFragment.get(position);
        }
        @Override
        public int getCount() {
            return pagerFragment.size();
        }
        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }
}
